/* eslint-disable react/prop-types */
import React, { useEffect } from 'react'
import { useImmer } from 'use-immer'
import {getAgoAt, storage} from '@/utils/utils'
import { DeleteOutlined } from '@ant-design/icons'
import messageModel from 'pages/model/message'
import Link from 'next/link'
import articlesModel from 'pages/model/articles'
import { Comment, Avatar, Form, Button, List, Input, Tooltip, Empty, Divider } from 'antd'
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
import noComment from '@/public/images/noComment.svg'

const { TextArea } = Input

const CommentList = ({ comments }) => (  
  <List
    dataSource={comments}
    itemLayout="horizontal"
    renderItem={props => <Comment {...props} />}
  />
)

const Editor = ({ onChange, onSubmit, submitting, value }) => (
  <>
    <Form.Item>
      <TextArea rows={4} className="comment-textArea" onChange={onChange} value={value} />
    </Form.Item>
    <Form.Item>
      <Button htmlType="submit" loading={submitting} onClick={onSubmit} type="primary">
        发表评论
      </Button>
    </Form.Item>
  </>
)

function ArticlesComment (props) {
  const { id, userId } = props
  const userInfo = JSON.parse(storage.get('next_blog_userInfo'))
  const [commentsList, setCommentsList] = useImmer({
    comments: [],
    submitting: false,
    value: '',
  })

  // 获取文章评论列表
  const getArticleCommentList = () => {
    articlesModel.getArticleCommentList({
      data: {id}
    }).then(({datas}) => {
      if (datas && datas.list) {
        let listData = []
        datas.list.length &&  datas.list.forEach((item) => {
          listData.push({
            author: <Link prefetch href={{pathname: '/user-info', query: {id: item.userId}}}><span style={{cursor: 'pointer'}}>{item.username}</span></Link>,
            avatar: item.avatar,
            content: <p>{item.content}</p>,
            actions: item.userId === userInfo.id ? ([
              <Tooltip key="comment-basic-like" title="删除此条评论">
                <span >
                  {/*  eslint-disable-next-line no-use-before-define */}
                  <Button type="text" onClick={() => deleteArticleComment(item.id)} danger icon={<DeleteOutlined></DeleteOutlined>}>删除</Button>
                </span>
              </Tooltip>
            ]) : <></>,
            datetime: (
              <Tooltip title={getAgoAt(item.createTime)}>
                <span>{getAgoAt(item.createTime)}</span>
              </Tooltip>
            )
          })
        })
        setCommentsList(data => {
          data.comments = [...listData]
        })
      }
    })
  }
  useEffect(() => {
    if (id) {
      getArticleCommentList()
    }
  }, [])
  const deleteArticleComment = (_id) => {
    articlesModel.deleteArticleComment({
      data: {
        id: _id,
        articleId: id
      }
    }).then(data => {
      if (data.success) {
        setCommentsList(data => {
          data.value = ''
          data.submitting = false
        })
        getArticleCommentList()
      }
    })
  }

  const handleSubmit = () => {
    if (!commentsList.value) {
      return
    }
    setCommentsList(data => {
      data.submitting = true
    })
    setTimeout(() => {
      articlesModel.addArticleComment({
        data: {
          articleId: id,
          loginId: userInfo.id,
          content: commentsList.value
        }
      }).then(data => {
        if (data.success) {
          setCommentsList(data => {
            data.value = ''
            data.submitting = false
          })
          getArticleCommentList()
        }
      })
      if ((JSON.parse(storage.get('next_blog_userInfo'))?.id !== userId)) {
        messageModel.addMessage({
          data: {
            loginId: JSON.parse(storage.get('next_blog_userInfo'))?.id,
            articleId: Number(id),
            type: 4,
            userId: userId
          }
        }).then(data => {
          console.log(data)
        })
      }
    }, 1000)
  }
  const handleChange = e => {
    setCommentsList(data => {
      data.value = e.target.value
    })
  }

  return (
    <>
      {commentsList.comments.length > 0 ? 
        <>
          <Divider>全部评论({commentsList.comments.length})</Divider>
          <CommentList comments={commentsList.comments} />
        </>
        :
        <>
          <Divider>暂无评论</Divider>
          <Empty
            image={noComment.src}
            imageStyle={{
              height: 60,
            }}
            description={
              <span style={{color: '#808795'}}>
              沙发还在,快来抢啊~
              </span>
            }
          >
          </Empty> 
        </>
      }
      <Comment
        avatar={<Avatar src={userInfo?.avatar} alt="User" />}
        content={
          <Editor
            onChange={(e) => handleChange(e)}
            onSubmit={(e) => handleSubmit(e)}
            submitting={commentsList.submitting}
            value={commentsList.value}
          />
        }
      />
    </>
  )
}

export default ArticlesComment